package com.androidxmpp.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidxmpp.R;
import com.androidxmpp.config.PreferenceConstants;
import com.androidxmpp.db.RosterProvider;
import com.androidxmpp.db.RosterProvider.RosterConstants;
import com.androidxmpp.model.Group;
import com.androidxmpp.model.Roster;
import com.androidxmpp.util.LogUtil;
import com.androidxmpp.util.PreferenceUtils;
import com.androidxmpp.util.StatusMode;

/**
 * 好友列表
 * @author chen_fulei
 *
 */
public class UserListAdapter extends BaseExpandableListAdapter {

	// 不在线状态
	private static final String OFFLINE_EXCLUSION = RosterConstants.STATUS_MODE
			+ " != " + StatusMode.offline.ordinal();
	// 在线人数
	private static final String COUNT_AVAILABLE_MEMBERS = "SELECT COUNT() FROM "
			+ RosterProvider.TABLE_ROSTER
			+ " inner_query"
			+ " WHERE inner_query."
			+ RosterConstants.GROUP
			+ " = "
			+ RosterProvider.QUERY_ALIAS
			+ "."
			+ RosterConstants.GROUP
			+ " AND inner_query." + OFFLINE_EXCLUSION;
	// 总人数
	private static final String COUNT_MEMBERS = "SELECT COUNT() FROM "
			+ RosterProvider.TABLE_ROSTER + " inner_query"
			+ " WHERE inner_query." + RosterConstants.GROUP + " = "
			+ RosterProvider.QUERY_ALIAS + "." + RosterConstants.GROUP;
	private static final String[] GROUPS_QUERY_COUNTED = new String[] {
			RosterConstants._ID,
			RosterConstants.GROUP,
			"(" + COUNT_AVAILABLE_MEMBERS + ") || '/' || (" + COUNT_MEMBERS
					+ ") AS members" };
	// 联系人查询序列
	private static final String[] ROSTER_QUERY = new String[] {
			RosterConstants._ID, RosterConstants.JID, RosterConstants.ALIAS,
			RosterConstants.STATUS_MODE, RosterConstants.STATUS_MESSAGE, };

	private Context mContext;
	private ContentResolver mContentResolver;
	private List<Group> mGroupList;
	private boolean mIsShowOffline;// 是否显示离线联系人
	private LayoutInflater mInflater;
	private HashMap<Integer, Integer> groupStatusMap;

	public UserListAdapter(Context mContext) {
		this.mContext = mContext;
		mContentResolver = mContext.getContentResolver();
		mGroupList = new ArrayList<Group>();
		groupStatusMap = new HashMap<Integer, Integer>();
		mInflater = LayoutInflater.from(mContext);
		mIsShowOffline = PreferenceUtils.getPrefBoolean(mContext, PreferenceConstants.SHOW_OFFLINE, true);
		
	}
	
	//獲取好友列表

	public void requery() {
		if (mGroupList != null && mGroupList.size() > 0)
			mGroupList.clear();
		// 是否显示在线人数

		mIsShowOffline = PreferenceUtils.getPrefBoolean(mContext,
				PreferenceConstants.SHOW_OFFLINE, true);
		String selectWhere = null;
		if (!mIsShowOffline)
			selectWhere = OFFLINE_EXCLUSION;
		Cursor groupCursor = mContentResolver.query(RosterProvider.GROUPS_URI,
				GROUPS_QUERY_COUNTED, selectWhere, null, RosterConstants.GROUP);
		groupCursor.moveToFirst();
		while (!groupCursor.isAfterLast()) {
			Group group = new Group();
			group.setGroupName(groupCursor.getString(groupCursor
					.getColumnIndex(RosterConstants.GROUP)));
			group.setMembers(groupCursor.getString(groupCursor
					.getColumnIndex("members")));
			mGroupList.add(group);
			groupCursor.moveToNext();
		}
		groupCursor.close();
		LogUtil.i("cursor size = " + mGroupList.size());
		notifyDataSetChanged();
	}

	protected List<Roster> getChildrenRosters(String groupname) {
		// Given the group, we return a cursor for all the children within

		// that group

		List<Roster> childList = new ArrayList<Roster>();

		String selectWhere = RosterConstants.GROUP + " = ?";
		if (!mIsShowOffline)
			selectWhere += " AND " + OFFLINE_EXCLUSION;
		Cursor childCursor = mContentResolver.query(RosterProvider.CONTENT_URI,
				ROSTER_QUERY, selectWhere, new String[] { groupname }, null);
		childCursor.moveToFirst();
		while (!childCursor.isAfterLast()) {
			Roster roster = new Roster();
			roster.setJid(childCursor.getString(childCursor
					.getColumnIndexOrThrow(RosterConstants.JID)));
			roster.setAlias(childCursor.getString(childCursor
					.getColumnIndexOrThrow(RosterConstants.ALIAS)));
			roster.setStatusMessage(childCursor.getString(childCursor
					.getColumnIndexOrThrow(RosterConstants.STATUS_MESSAGE)));
			roster.setStatusMode(childCursor.getString(childCursor
					.getColumnIndexOrThrow(RosterConstants.STATUS_MODE)));
			childList.add(roster);
			childCursor.moveToNext();
		}
		childCursor.close();
		return childList;
	}

	

	@Override
	public Roster getChild(int groupPosition, int childPosition) {
		return getChildrenRosters(mGroupList.get(groupPosition).getGroupName()).get(childPosition);
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return childPosition;
	}

	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isExpanded, View convertView, ViewGroup parent) {
			
			Roster roster = getChild(groupPosition, childPosition);
			int mode_status = Integer.parseInt(roster.getStatusMode());
			String u_id = roster.getJid();
			ViewHolderChild  viewHolder;
			if(convertView == null ){
				LogUtil.i("UserListAdapter", "new Child");
				 viewHolder = new ViewHolderChild();
				 convertView = mInflater.inflate(R.layout.user_chrild_item, null);
				 viewHolder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon);
				 viewHolder.txt_name = (TextView) convertView.findViewById(R.id.txt_name);
				 viewHolder.txt_status = (TextView) convertView.findViewById(R.id.txt_status);
				 viewHolder.img_status_type = (ImageView) convertView.findViewById(R.id.img_status_type);
				 viewHolder.img_icon_status = (ImageView) convertView.findViewById(R.id.img_icon_state);
				 
				 convertView.setTag(viewHolder);
			}else{
				LogUtil.i("UserListAdapter",  "get child form case");
				viewHolder  = (ViewHolderChild) convertView.getTag();
			}
			
			viewHolder.txt_name.setText(roster.getAlias());
			String txt_status_str =  TextUtils.isEmpty(roster.getStatusMessage()) ? mContext.getString(R.string.status_offline) : roster.getStatusMessage();
			viewHolder.txt_status.setText("["+txt_status_str+"]");
			setImageView(viewHolder.img_icon, viewHolder.img_icon_status, viewHolder.img_status_type, roster.getStatusMode());
			
		return convertView;
	}
	
	//设置头像...
	public void setImageView(ImageView icon_head, ImageView icon_status, ImageView icon_status_type, String status_Str) {
			int statusMode = Integer.parseInt(status_Str);
			int presenceMode = getIconForPresenceMode(statusMode);
			
			if(presenceMode == -1){
				  icon_head.setImageResource(R.drawable.ic_launcher);
				  icon_status.setImageResource(R.drawable.status_leave);
				  icon_status_type.setImageResource(R.drawable.terminal_icon_phone_online);
			}
			
			//还要判断用什么机子上的和头像的改变
			 icon_head.setImageResource(R.drawable.ic_launcher);
			 icon_status_type.setImageResource(R.drawable.terminal_icon_phone_online);
			 icon_status.setImageResource(presenceMode);
	}
	
	public int getIconForPresenceMode(int presenceMode){
		return StatusMode.values()[presenceMode].getDrawableId();
	}

	private class ViewHolderChild{
		ImageView img_icon;//头像
		TextView txt_name;// 名称
		TextView txt_status;//状态
		ImageView img_icon_status;//状态图片
		ImageView img_status_type;//
	}

	@Override
	public int getChildrenCount(int childPosition) {
		if(mGroupList.size() <=0){
			return 0;
		}
		
		return getChildrenRosters(mGroupList.get(childPosition).getGroupName()).size();
	}

	@Override
	public Group getGroup(int groupPosition) {
		return mGroupList.get(groupPosition);
	}

	@Override
	public int getGroupCount() {
		return mGroupList.size();
	}

	@Override
	public long getGroupId(int groupPosition) {
		return groupPosition;
	}

	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
			Group group  = getGroup(groupPosition);
			ViewHolderParent viewHolder;
			
			if(convertView == null){
				viewHolder = new ViewHolderParent();
				convertView = mInflater.inflate(R.layout.user_parent_item, null);
				viewHolder.txt_parent_name =(TextView) convertView.findViewById(R.id.txt_parent_name);
				viewHolder.txt_number = (TextView) convertView.findViewById(R.id.txt_number);
				viewHolder.group_indicator = (ImageView) convertView.findViewById(R.id.group_indicator);
				
				convertView.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolderParent) convertView.getTag();
			}
			
			viewHolder.txt_parent_name.setText(TextUtils.isEmpty(group.getGroupName()) ? mContext.getString(R.string.default_group) : group.getGroupName());
			viewHolder.txt_number.setText(group.getMembers());
			
			if(isExpanded){
				viewHolder.group_indicator.setImageResource(R.drawable.indicator_expanded);
			}else{
				viewHolder.group_indicator.setImageResource(R.drawable.indicator_unexpanded);
			}
		
		return convertView;
	}
	
	private class ViewHolderParent{
		TextView txt_parent_name;
		TextView txt_number;
		ImageView group_indicator;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return true;
	}

}
